package com.playball.lottery;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.WindowManager;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.playball.lottery.customview.LoadingDialog;
import com.playball.lottery.customview.ShowCustomDialog;
import com.playball.lottery.eventmanger.EventManager;
import com.playball.lottery.eventmanger.EventManager.EventHandler;
import com.playball.lottery.eventmanger.EventType;
import com.playball.lottery.fragment.frm.HeMaiMainFragment;
import com.playball.lottery.fragment.frm.HomeFragment;
import com.playball.lottery.fragment.frm.KjinfoMainFragment;
import com.playball.lottery.fragment.frm.LoginFragment;
import com.playball.lottery.fragment.frm.ScoreMainFragment;
import com.playball.lottery.fragment.frm.Tab1Fragment;
import com.playball.lottery.fragment.frm.UserCenterFragment;
import com.playball.lottery.fragment.frm.WebFragment;
import com.playball.lottery.nt.AppVersionConfig;
import com.playball.lottery.nt.GetRequestParams;
import com.playball.lottery.nt.MyTask;
import com.playball.lottery.sessions.SessionManager;
import com.playball.lottery.util.ConvertJsonToList;
import com.playball.lottery.util.Logger;
import com.playball.lottery.util.LotConstants;
import com.playball.lottery.util.PhoneInfo;
import com.playball.lottery.util.SysApplication;


public class JddMainActivity extends FragmentActivity implements LotConstants {
	protected static final String TAG = "JddMainActivity";

	private FragmentTransaction ft;
	private RadioGroup radioGroup;
	private Tab1Fragment tab1Fragment;
	private HomeFragment homeFragment;
	private HeMaiMainFragment heMaiMainFragment;
	private KjinfoMainFragment kjinfoMainFragment;
	private ScoreMainFragment scoreMainFragment;
	private LoginFragment loginFragment;
	private UserCenterFragment userCenterFragment;
	private WebFragment webFragment;

	public int scr_w;
	public int scr_h;

	private RadioButton rb_score,rb_home,rb_buy_hall,rb_kaijiang,rb_userhome,rb_co_buy;
	private RadioButton rb_huodong;

	// /* 活动HTTP地址 */
	// private String rb_huodong_url;
	// /* 活动是否结束 */
	// private boolean rb_huodong_isclose;

	/************************************/
	public int type; // 根据tpye不同显示不同的界面 0世界杯、1购彩大厅、2合买大厅、3开奖公告、4个人中心;
	private MainService mService;

	private boolean mIsBound;

	private long mExitTime = 0;

	PhoneInfo phoneInfo;
	private SharedPreferences sp;

	// 下载apk的name
	private String downLoadName = "";

	// Session Manager Class
	SessionManager session;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_jddmain);
		ImageLoader imageLoader = ImageLoader.getInstance();
		imageLoader.init(ImageLoaderConfiguration.createDefault(this));
		// Session Manager
		session = new SessionManager(getApplicationContext());

		MainService.start(this);

		DisplayMetrics metrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metrics);
		scr_w = metrics.widthPixels;
		scr_h = metrics.heightPixels;
		Logger.e(TAG, "scr_w:" + scr_w + "	scr_h:" + scr_h);

		radioGroup = (RadioGroup) findViewById(R.id.mh_bottom_menu);
		radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				// TODO Auto-generated method stub
				radioGroupChecked(checkedId);
			}
		});

		// modify by rainy do bot show bifen
		rb_huodong = (RadioButton) findViewById(R.id.rb_huodong);
		// rb_huodong.setVisibility(View.GONE);
		rb_score = (RadioButton) findViewById(R.id.rb_score);
		// rb_score.setVisibility(View.VISIBLE);
		rb_home= (RadioButton) findViewById(R.id.rb_home);
		rb_co_buy= (RadioButton) findViewById(R.id.rb_co_buy);
		rb_buy_hall=(RadioButton) findViewById(R.id.rb_buy_hall);
		rb_userhome=(RadioButton) findViewById(R.id.rb_userhome);
		rb_kaijiang=(RadioButton) findViewById(R.id.rb_kaijiang);
		setChecked(R.id.rb_home);

//		doTasks();

		// if(!StartupActivity.rb_huodong_isclose) {
		// rb_huodong.setVisibility(View.VISIBLE);
		// rb_score.setVisibility(View.GONE);
		// }
		/*
		 * 事件控制用户登入状态
		 */
		EventManager.getInstance().registEventHandler(EventType.EV_BLL_lOGION_REFRESHUSEREVENT, new EventHandler() {

			@Override
			public void excute(Object obj) {
				// TODO Auto-generated method stub
				refreshUserEvent();

				syncWap();
			}
		});

		/**
		 * 通知刷新WAP同步信息
		 */
		EventManager.getInstance().registEventHandler(EventType.EV_BLL_UI_MAIN_LOT_REFRESH, new EventHandler() {
			@Override
			public void excute(Object obj) {
				// TODO Auto-generated method stub
				syncWap();
			}
		});

	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		// if(userCenterFragment != null) {
		// if(!userCenterFragment.isHidden()) {
		// if(!ApplicationData.getInstance().isUserLogin()) {
		// refreshUserEvent();
		// }
		// }
		// }

		switch (radioGroup.getCheckedRadioButtonId()) {
			case R.id.rb_userhome:
				ft = getSupportFragmentManager().beginTransaction();

				if (ApplicationData.getInstance().isUserLogin()) {
					if (loginFragment != null) {
						ft.hide(loginFragment);
						loginFragment.onPause();
					}
					if (userCenterFragment == null) {
						userCenterFragment = new UserCenterFragment();
						ft.add(R.id.content_frame, userCenterFragment, UserCenterFragment.TAG);
					} else {
						ft.show(userCenterFragment);
						userCenterFragment.onResume();
					}
				} else {
					if (userCenterFragment != null) {
						ft.hide(userCenterFragment);
						userCenterFragment.onPause();
					}
					if (loginFragment == null) {
						loginFragment = new LoginFragment();
						ft.add(R.id.content_frame, loginFragment, LoginFragment.TAG);
					} else {
						ft.show(loginFragment);
						loginFragment.onResume();
					}
				}
				// ft.commit();
				ft.commitAllowingStateLoss();
				break;
		}

		refreshView();

	}

	public void onPause() {
		super.onPause();

	}

	/**
	 * 切换栏目
	 *
	 * @param checkedId
	 */
	private void radioGroupChecked(int checkedId) {
		ft = getSupportFragmentManager().beginTransaction();
		// ft.setCustomAnimations(R.anim.go_in, 0, 0, R.anim.go_out);

		// 隐藏其它显示状态的Fragment，确保当前只有一个Fragment处于活动状态
		if (getSupportFragmentManager().getFragments() != null) {
			Fragment fragment = null;
			for (int i = 0; i < getSupportFragmentManager().getFragments().size(); i++) {
				fragment = getSupportFragmentManager().getFragments().get(i);
				// if(fragment instanceof LunBoFragment) {
				// //嵌套的轮播广告，不作处理
				// } else {
				if (!fragment.isHidden()) {
					ft.hide(fragment);
					fragment.onPause();
				}
				// }
			}
		}

		// WAP活动页，键盘被挡问题特殊处理
		if (checkedId != R.id.rb_huodong) {
			getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN | WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
		}

		switch (checkedId) {
			//首页
			case R.id.rb_home:
				if (session.isLoggedIn()){
					if (tab1Fragment == null) {
						tab1Fragment = new Tab1Fragment();
						ft.add(R.id.content_frame, tab1Fragment, Tab1Fragment.TAG);
					} else {
						ft.show(tab1Fragment);
						tab1Fragment.onResume();
					}
				} else {
					if (loginFragment == null) {
						loginFragment = new LoginFragment();
						ft.add(R.id.content_frame, loginFragment, LoginFragment.TAG);
					} else {
						ft.show(loginFragment);
						loginFragment.onResume();
					}
				}

				rb_home.setTextColor(getResources().getColor(R.color.red_home));
				rb_co_buy.setTextColor(getResources().getColor(R.color.yhzx_sc_item_describe));
				rb_userhome.setTextColor(getResources().getColor(R.color.yhzx_sc_item_describe));
				rb_kaijiang.setTextColor(getResources().getColor(R.color.yhzx_sc_item_describe));

				rb_home.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.home_hover, 0, 0);
				rb_kaijiang.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.bag, 0, 0);
				rb_co_buy.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.fuwu, 0, 0);
				rb_userhome.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.wo, 0, 0);


				break;
//			case R.id.rb_huodong:
//				if (webFragment == null) {
//					webFragment = new WebFragment();
//					Bundle bundle = new Bundle();
//					bundle.putString("wap_url", StartupActivity.rb_huodong_url);
//					webFragment.setArguments(bundle);
//					ft.add(R.id.content_frame, webFragment, WebFragment.TAG);
//				} else {
//					ft.show(webFragment);
//					webFragment.onResume();
//				}
//				getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE | WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
//				break;
			case R.id.rb_buy_hall:
				if (session.isLoggedIn()){
					if (homeFragment == null) {
						homeFragment = new HomeFragment();
						ft.add(R.id.content_frame, homeFragment, HomeFragment.TAG);
					} else {
						ft.show(homeFragment);
						homeFragment.onResume();
					}
				} else {
					if (loginFragment == null) {
						loginFragment = new LoginFragment();
						ft.add(R.id.content_frame, loginFragment, LoginFragment.TAG);
					} else {
						ft.show(loginFragment);
						loginFragment.onResume();
					}
				}

				break;
			//合买
			case R.id.rb_co_buy:
				if (heMaiMainFragment == null) {
					heMaiMainFragment = new HeMaiMainFragment();
					ft.add(R.id.content_frame, heMaiMainFragment, HeMaiMainFragment.TAG);
				} else {
					ft.show(heMaiMainFragment);
					heMaiMainFragment.onResume();
				}

				rb_home.setTextColor(getResources().getColor(R.color.yhzx_sc_item_describe));
				rb_co_buy.setTextColor(getResources().getColor(R.color.red_home));
				rb_userhome.setTextColor(getResources().getColor(R.color.yhzx_sc_item_describe));
				rb_kaijiang.setTextColor(getResources().getColor(R.color.yhzx_sc_item_describe));

				rb_home.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.home, 0, 0);
				rb_co_buy.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.bag_hover, 0, 0);
				rb_kaijiang.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.fuwu, 0, 0);
				rb_userhome.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.wo, 0, 0);
				break;
			//服务
			case R.id.rb_kaijiang:
				if (kjinfoMainFragment == null) {
					kjinfoMainFragment = new KjinfoMainFragment();
					ft.add(R.id.content_frame, kjinfoMainFragment, KjinfoMainFragment.TAG);
				} else {
					ft.show(kjinfoMainFragment);
					kjinfoMainFragment.onResume();
				}

				rb_home.setTextColor(getResources().getColor(R.color.yhzx_sc_item_describe));
				rb_co_buy.setTextColor(getResources().getColor(R.color.yhzx_sc_item_describe));
				rb_userhome.setTextColor(getResources().getColor(R.color.yhzx_sc_item_describe));
				rb_kaijiang.setTextColor(getResources().getColor(R.color.red_home));

				rb_home.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.home, 0, 0);
				rb_co_buy.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.bag, 0, 0);
				rb_kaijiang.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.fuwu_hover, 0, 0);
				rb_userhome.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.wo, 0, 0);
				break;
//			case R.id.rb_score:
//				if (scoreMainFragment == null) {
//					scoreMainFragment = new ScoreMainFragment();
//					ft.add(R.id.content_frame, scoreMainFragment, ScoreMainFragment.TAG);
//				} else {
//					ft.show(scoreMainFragment);
//					scoreMainFragment.onResume();
//				}
//				break;
			case R.id.rb_userhome:
//				if (ApplicationData.getInstance().isUserLogin()) {
					if (session.isLoggedIn()){
					if (userCenterFragment == null) {
						userCenterFragment = new UserCenterFragment();
						ft.add(R.id.content_frame, userCenterFragment, UserCenterFragment.TAG);
					} else {
						ft.show(userCenterFragment);
						userCenterFragment.onResume();
					}
				} else {
					if (loginFragment == null) {
						loginFragment = new LoginFragment();
						ft.add(R.id.content_frame, loginFragment, LoginFragment.TAG);
					} else {
						ft.show(loginFragment);
						loginFragment.onResume();
					}
				}

				rb_home.setTextColor(getResources().getColor(R.color.yhzx_sc_item_describe));
				rb_co_buy.setTextColor(getResources().getColor(R.color.yhzx_sc_item_describe));
				rb_userhome.setTextColor(getResources().getColor(R.color.red_home));
				rb_kaijiang.setTextColor(getResources().getColor(R.color.yhzx_sc_item_describe));

				rb_home.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.home, 0, 0);
				rb_co_buy.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.bag, 0, 0);
				rb_kaijiang.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.fuwu, 0, 0);
				rb_userhome.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.wo_hover, 0, 0);
				refreshView();
				break;
			default:
				break;
		}
		ft.commit();
	}

	/**
	 * 刷新用户登录退出状态
	 */
	public void refreshUserEvent() {
		radioGroupChecked(R.id.rb_home);
	}

	/**
	 * 设置当前选中项
	 *
	 * @param resId
	 */
	public void setChecked(int resId) {
		RadioButton rb = (RadioButton) findViewById(resId);
		rb.setChecked(true);
	}

	/**
	 * 活动加载
	 */
	/*
	 * private void loadHuoDong() { HuoDongLoader loader = new HuoDongLoader();
	 * String[] dyn = new String[2]; JSONObject params1 = new JSONObject();
	 * dyn[0] = params1.toString(); dyn[1] = "218"; loader.execute(dyn); }
	 */

	/**
	 * 活动异步加载
	 */
	/*
	 * private class HuoDongLoader extends AsyncTask<String, Integer, String> {
	 *
	 * @Override protected void onPreExecute() { // TODO Auto-generated method
	 * stub super.onPreExecute(); rb_huodong_url = ""; rb_huodong_isclose =
	 * true; }
	 *
	 * @Override protected String doInBackground(String... params) { // TODO
	 * Auto-generated method stub String strResult; String action = params[1];
	 * strResult = GetRequestParams.getRequestResult(params[0], action,
	 * JddMainActivity.this); return strResult; }
	 *
	 * @Override protected void onPostExecute(String result) { // TODO
	 * Auto-generated method stub super.onPostExecute(result); try { if(result
	 * != null) { Logger.e(TAG, result); JSONTokener jsonParser = new
	 * JSONTokener(result); JSONObject js; js = (JSONObject)
	 * jsonParser.nextValue(); if (js.getInt("Code") == 0) { Map<String, Object>
	 * map = new HashMap<String, Object>(); map =
	 * ConvertJsonToList.getMap(js.getString("Data"));
	 *
	 * rb_huodong_url = map.get("wapurl").toString(); rb_huodong_isclose =
	 * "true".equals(map.get("isclose").toString());
	 *
	 * if(!rb_huodong_isclose) { rb_huodong.setVisibility(View.VISIBLE);
	 * rb_score.setVisibility(View.GONE); } } } } catch (Exception e) { // TODO
	 * Auto-generated catch block e.printStackTrace(); } }
	 *
	 * }
	 */

	/**
	 * 刷新页面
	 */
	public void refreshView() {
		// Log.d("JddMainActivity", "->refreshView");
//		if (ApplicationData.getInstance().isUserLogin()) {
		if (session.isLoggedIn()){
			((RadioButton) findViewById(R.id.rb_userhome)).setText("个人中心");
		} else {
			((RadioButton) findViewById(R.id.rb_userhome)).setText("登录注册");
		}
	}

	private void safelyRestoreUi() {
		// runOnUiThread(new Runnable() {
		// @Override
		// public void run() {
		// restoreUI();
		// }
		// });
	}

	private void restoreUI() {
		// Log.d("JddMainActivity", "->restoreUI mainStatus:" +
		// mainStatus.toString());
		// switch (mainStatus) {
		// case TEST:
		// testRoot.restoreUi();
		// break;
		// case TEST1:
		// testmainRoot1.restoreUi();
		// break;
		// case FRMWORK_BODY:
		// frmWork.safelyRestoreUi();
		// break;
		// default:
		// break;
		// }
	}

	public void addTask(MyTask myTask) {
		// Log.d("JddMainActivity", "addTask:" + myTask.getTaskId().name());
		// DoMyTask task = new DoMyTask(myTask);
		// task.execute("");
	}

	/**
	 * 执行老版本各种加载任务
	 */
	private void doTasks() {
		// TODO Auto-generated method stub

		sp = this.getSharedPreferences("bFitstLoad", MODE_PRIVATE);

		processDataCreate();



		phoneInfo = new PhoneInfo(this);
		GetRequestParams.setUUid(phoneInfo.getIme());
		ApplicationData.APPVERSION = getVersion();

		ApplicationInfo info;
		try {
			info = this.getPackageManager().getApplicationInfo(getPackageName(), PackageManager.GET_META_DATA);
			String msg = info.metaData.get("CmdID").toString();
			String[] msgs = msg.split(",");
			if (msgs.length > 1) {
				ApplicationData.getInstance().setCommenderID(Integer.parseInt(msgs[0]));
				ApplicationData.getInstance().setCommenderName(msgs[1]);
			} else {
				ApplicationData.getInstance().setCommenderID(Integer.parseInt(msg));
				ApplicationData.getInstance().setCommenderName("");
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			// e.printStackTrace();
		}
		int temp = sp.getInt("firstOpen", 0);
		if (temp != phoneInfo.getVCode()) {
			AsyncLoader task = new AsyncLoader();
			String[] parms = new String[2];
			JSONObject params = new JSONObject();
			try {
				// 设置请求所需参数
				params.put("Ime", phoneInfo.getIme());
				params.put("MMN", phoneInfo.getMMN());
				params.put("MPN", phoneInfo.getMPN());
				params.put("OSV", phoneInfo.platformVersion());
				params.put("PV", phoneInfo.getVName());
				params.put("MNu", phoneInfo.getNativePhoneNumber());
			} catch (JSONException ex) {
				// TODO Auto-generated catch block
				Logger.e("error", ex.toString());
			}
			parms[1] = params.toString();
			parms[0] = "3";// 2
			task.execute(parms);

		}

		//doUpdate();
	}

	private void doUpdate() {
		AsyncLoaderUpdate asyncLoader = new AsyncLoaderUpdate();
		String[] dyn = new String[2];
		JSONObject params1 = new JSONObject();
		try {
			// 设置请求所需参数
			params1.put("CmdID", ApplicationData.getInstance().getCommenderID());
		} catch (JSONException ex) {
		}
		dyn[0] = params1.toString();
		dyn[1] = "1";
		asyncLoader.execute(dyn);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			/*if (_SlidingMenu.isMenuShowing()) {
				_SlidingMenu.showContent();
			} else */if (webFragment != null && !webFragment.isHidden() && webFragment.canGoBack()) {
				webFragment.goBack();
			} else {
				if ((System.currentTimeMillis() - mExitTime) > 2000) {// 如果两次按键时间间隔大于2000毫秒，则不退出
					Toast.makeText(this, R.string.again_according_to_exit_the_program, Toast.LENGTH_SHORT).show();
					Intent intent = new Intent(this, DownService.class);
					stopService(intent);
					mExitTime = System.currentTimeMillis();// 更新mExitTime
				} else {
					SysApplication.getInstance().exit();
				}
			}
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onNewIntent(Intent intent) {
		// TODO Auto-generated method stub
		super.onNewIntent(intent);
		setIntent(intent);
		processDataNew();
	}

	// 推送类型TYPE 0世界杯、1购彩大厅、2合买大厅、3开奖公告、4个人中心、5比分直播
	private void processDataCreate() {
		Intent intent = getIntent();
		int type = intent.getIntExtra("type", 0);
		switch (type) {
			case 0:
			case 1:
				setChecked(R.id.rb_home);
				break;
			case 2:
				setChecked(R.id.rb_co_buy);
				break;
			case 3:
				setChecked(R.id.rb_kaijiang);
				break;
			case 4:
				setChecked(R.id.rb_userhome);
				break;
			case 5:
				setChecked(R.id.rb_score);
				break;
			default:
				setChecked(R.id.rb_home);
				break;
		}
	}

	private void processDataNew() {
		Intent intent = getIntent();
		int type = intent.getIntExtra("type", 0);
		switch (type) {
			case 0:
			case 1:
				setChecked(R.id.rb_home);
				break;
			case 2:
				setChecked(R.id.rb_co_buy);
				break;
			case 3:
				setChecked(R.id.rb_kaijiang);
				break;
			case 4:
				setChecked(R.id.rb_userhome);
				break;
			case 5:
				setChecked(R.id.rb_score);
				break;
			default:
				setChecked(R.id.rb_home);
				break;
		}
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		Logger.d("JddMainActivity", "--------->onDestroy");
		Intent intent = new Intent(this, DownService.class);
		stopService(intent);
		ApplicationData.getInstance().stopTimerTaskPerS();
		// doUnbindService();
		MainService.stop(this);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
			case REQ_RECHARGE_LIST_FROM_HOMEFRM:
				break;
			case REQ_RECHARGE_LIST_FROM_USER_CENTER_FRM:
				break;
			case REQ_ADDMORELOT_FROM_MAINHOME:
				if (resultCode == RESULT_OK) {
					refreshView();
				}
				break;
			case REQ_BUYLOT_FROM_MAINHOME:
				break;
			case REQ_REGISTER_FROM_HOMEFRM:
				if (resultCode == RESULT_OK) {
					if (data.getIntExtra("whichButton", 0) == 1) {
						refreshUserEvent();
					} else {
						setChecked(R.id.rb_home);
						refreshView();
					}
				}
				break;
		}

	}

	public String getVersion() {
		String version = "1.0.0";
		PackageManager packageManager = getPackageManager();
		try {
			PackageInfo packageInfo = packageManager.getPackageInfo(getPackageName(), 0);
			version = packageInfo.versionName;
		} catch (NameNotFoundException e) {
			// e.printStackTrace();
		}
		return version;
	}

	class AsyncLoader extends AsyncTask<String, Integer, String> {// 继承AsyncTask

		public AsyncLoader() {
			super();
		}

		protected void onPreExecute() {
		}

		@Override
		protected String doInBackground(String... params) {
			String strResult;
			String action = params[0];
			strResult = GetRequestParams.getRequestResult(params[1], action, getApplicationContext());
			return strResult;
		}

		protected void onProgressUpdate(Integer... progress) {
		}

		protected void onPostExecute(String result) {
			try {
				if (result != null) {
					JSONTokener jsonParser = new JSONTokener(result);
					JSONObject js = (JSONObject) jsonParser.nextValue();
					if (Integer.parseInt(js.getString("Code")) == 0) {
						sp.edit().putInt("firstOpen", phoneInfo.getVCode()).commit();
					}
				}
			} catch (NumberFormatException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	/**
	 * 升级版本
	 *
	 * @author jddr
	 *
	 */
	class AsyncLoaderUpdate extends AsyncTask<String, Integer, String> {

		@Override
		protected String doInBackground(String... params) {
			// 处理后台执行的任务，在后台线程执行
			String strResult;
			// String param = new String();
			// 设置请求action
			String action = params[1];
			// 获取请求返回值
			strResult = GetRequestParams.getRequestResult(params[0], action, JddMainActivity.this);
			return strResult;
		}

		@Override
		protected void onCancelled() {
			// TODO Auto-generated method stub
			super.onCancelled();
		}

		protected void onPostExecute(String result) {
			if (result != null) {
				doNetget(result);
			}
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			// TODO Auto-generated method stub
			super.onProgressUpdate(values);
		}

	}

	List<Map<String, Object>> nDataList = new ArrayList<Map<String, Object>>();

	public void doNetget(String strResult) {
		try {
			JSONTokener jsonParser = new JSONTokener(strResult);
			JSONObject js = (JSONObject) jsonParser.nextValue();
			// 接下来的就是JSON对象的操作了
			if (Integer.parseInt(js.getString("Code")) == 0) {
				if ("".equals(js.getString("Data"))) {
				} else {
					nDataList = getNetData(strResult);
					String updateMes = "";
					int bupdate = 0;

					String newVerName = "";
					int newVerCode = 0;
					try {
						newVerCode = Integer.parseInt(String.valueOf(nDataList.get(0).get("verCode")));
						newVerName = String.valueOf(nDataList.get(0).get("verName"));
						bupdate = Integer.parseInt(String.valueOf(nDataList.get(0).get("bupdate")));
						String message = String.valueOf(nDataList.get(0).get("Message"));

						downLoadName = String.valueOf(nDataList.get(0).get("apkname"));

						JSONArray messArray = new JSONArray(message);
						for (int i = 0; i < messArray.length(); i++) {
							updateMes = updateMes + messArray.getString(i) + "\n";
						}
					} catch (Exception e) {
						e.printStackTrace();
						newVerCode = -1;
						newVerName = "";
						bupdate = 0;
					}
					int vercode = getVerCode(JddMainActivity.this);
					if (newVerCode > vercode) {
						if (bupdate == 1) { // 提示更新
							isMustUpgrade = false;
							doNewVersionUpdate(updateMes, downLoadName);
						} else if (bupdate < 0) { // 强制更新
							isMustUpgrade = true;
							doNewVersionUpdate2(updateMes, downLoadName);
						} else if (bupdate == 2) { // 不提示更新，放到用户检测更新中
							// doUpdate(downLoadName);
							stratService();
						}

					} else {
					}
				}
			} else {
				Toast.makeText(this, js.getString("Data"), Toast.LENGTH_SHORT).show();
			}
		} catch (JSONException e) {
		}
	}

	private List<Map<String, Object>> getNetData(String strResult) {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		try {
			JSONTokener jsonParser = new JSONTokener(strResult);
			JSONObject js = (JSONObject) jsonParser.nextValue();
			list = ConvertJsonToList.getList(js.getString("Data"));
			// Log.d("getNetData", list.toString());
		} catch (JSONException ex) {
			// ex.printStackTrace();
		}
		return list;
	}

	// 有检测到新版本，提示更新
	private void doNewVersionUpdate(String mes, final String name) {

		ShowCustomDialog dialog = new ShowCustomDialog.Builder(this).setTitle("软件更新").setMessage(mes)
				// 设置内容
				.setPositiveButton("暂不更新",// 设置确定按钮
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								stratService();
								dialog.cancel();
							}
						}).setNegativeButton("更新", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						dialog.cancel();
						doUpdate(name);
					}
				}).createCustomDialog();// 创建
		// 显示对话框
		dialog.setCanceledOnTouchOutside(false);
		dialog.show();
	}

	// 有检测到新版本，强制更新
	private void doNewVersionUpdate2(final String mes, final String name) {

		ShowCustomDialog dialog = new ShowCustomDialog.Builder(this).setTitle("软件更新").setMessage(mes)
				// 设置内容
				.setPositiveButton("取消",// 设置确定按钮
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								dialog.cancel();
								exitConfirm(mes, name);
							}
						}).setNegativeButton("更新", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						dialog.dismiss();
						doUpdate(name);
					}
				}).setOnCancelListener(new OnCancelListener() {

					@Override
					public void onCancel(DialogInterface dialog) {
						dialog.cancel();
						exitConfirm(mes, name);
					}
				}).createCustomDialog();// 创建
		// 显示对话框
		dialog.setCancelable(false);
		dialog.setCanceledOnTouchOutside(false);
		dialog.show();
	}

	private void exitConfirm(final String mes, final String name) {
		ShowCustomDialog dialog = new ShowCustomDialog.Builder(this).setTitle("温馨提示").setMessage("该版本太老啦，已无法正常使用，您真的狠心要退出么？")
				// 设置内容
				.setPositiveButton("取消",// 设置确定按钮
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								dialog.dismiss();
								doNewVersionUpdate2(mes, name);
							}
						}).setNegativeButton("确定", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						dialog.cancel();
						finish();
					}
				}).setMessageIcon(R.drawable.message_icon).createCustomDialog();
		dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
			@Override
			public void onCancel(DialogInterface dialog) {
				// TODO Auto-generated method stub
				doNewVersionUpdate2(mes, name);
			}
		});
		dialog.setCanceledOnTouchOutside(false);
		dialog.show();
	}

	LoadingDialog pBar;

	// 开始更新
	private void doUpdate(String name) {

		pBar = new LoadingDialog(this);
		// 如果当前不是wifi网络，允许用户取消下载
		// if(!AppUtils.isWifiConnected(this))
		{
			pBar.getDialog().setCancelable(true);
			pBar.getDialog().setOnCancelListener(new DialogInterface.OnCancelListener() {
				@Override
				public void onCancel(DialogInterface dialog) {
					// TODO Auto-generated method stub
					isCancelDownload = true;
				}
			});
		}
		// 下载新版本
		downFile(AppVersionConfig.UPDATE_SERVER + name);

	}

	boolean isCancelDownload;
	boolean isMustUpgrade;

	/************************************ service****szw */
	// 有新版本就跟新
	private void stratService() {
		// Intent intent = new Intent();
		// intent.setClass(getApplicationContext(),DownService.class);
		// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		// Bundle bundle = new Bundle();
		// bundle.putString("apkName", downLoadName);
		// intent.putExtras(bundle);
		// startService(intent);
	}

	/***************** end ****************************/

	// 下载新版本
	void downFile(final String url) {

		pBar.show();
		isCancelDownload = false;
		new Thread() {
			@SuppressWarnings("unused")
			public void run() {
				HttpClient client = new DefaultHttpClient();
				HttpGet get = new HttpGet(url);
				HttpResponse response;
				try {
					response = client.execute(get);
					HttpEntity entity = response.getEntity();
					long length = entity.getContentLength();
					int pBarmax = (int) entity.getContentLength() / 1024;
					pBar.setMax(pBarmax);
					InputStream is = entity.getContent();
					FileOutputStream fileOutputStream = null;
					if (is != null) {
						File file = new File(Environment.getExternalStorageDirectory(), AppVersionConfig.UPDATE_SAVENAME);
						fileOutputStream = new FileOutputStream(file);

						byte[] buf = new byte[1024];
						int ch = -1;
						int count = 0;
						while ((ch = is.read(buf)) != -1) {
							fileOutputStream.write(buf, 0, ch);
							count += ch;
							if (pBar.getMax() > (count / 1024)) {
								pBar.setProgress(count / 1024);
								// pBar.setSecondaryProgress(count / 1024);
							}
							if (isCancelDownload)
								break;
						}
					}
					fileOutputStream.flush();
					if (fileOutputStream != null) {
						fileOutputStream.close();
					}
					if (!isCancelDownload)
						down();
					else {
						// 如果是强制更新，继续弹出更新提示框
						if (isMustUpgrade) {
							doUpdate();
						}
					}

				} catch (IOException e) {
					// e.printStackTrace();
					pBar.cancel();
				}
			}

		}.start();
	}

	private Handler handler = new Handler();
	private static String packgeName = null;

	// 下载新版本后关闭
	void down() {
		handler.post(new Runnable() {
			public void run() {
				pBar.cancel();
				update();
			}
		});
	}

	// 下载新版本后安装
	void update() {
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory(), AppVersionConfig.UPDATE_SAVENAME)),
				"application/vnd.android.package-archive");
		startActivity(intent);
		finish();
	}

	// 获取Code
	public static int getVerCode(Context context) {
		int verCode = -1;
		try {
			if (packgeName == null)
				packgeName = context.getPackageName();
			verCode = context.getPackageManager().getPackageInfo(packgeName, 0).versionCode;
		} catch (NameNotFoundException e) {
		}
		return verCode;
	}

	// 获取Name
	public static String getVerName(Context context) {
		String verName = "";
		try {
			if (packgeName == null)
				packgeName = context.getPackageName();
			verName = context.getPackageManager().getPackageInfo(packgeName, 0).versionName;
		} catch (NameNotFoundException e) {
		}
		return verName;

	}

	public void syncWap() {
		if (webFragment != null) {
			webFragment.syncCookies();
		}
	}

}
